package com.china08.yxyapi.api.manage.tec.teaching.weikecheng.weike;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyKnowledge;
import com.china08.yxyapi.entity.db.res.YxyResBook;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.db.res.YxyResResourceForEsReindex;
import com.china08.yxyapi.entity.db.res.YxyResWeikeKnow;
import com.china08.yxyapi.entity.mg.mistakes.TeaMistakesQues;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyKnowledgeRepository;
import com.china08.yxyapi.repository.db.YxyResBookRepository;
import com.china08.yxyapi.repository.db.YxyResResourceForEsReindexRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.db.YxyResWeikeKnowRepository;
import com.china08.yxyapi.repository.mg.mistakes.TeaMistakesQuesRepository;
import com.china08.yxyapi.util.EsResourceUpdateUtil;

/**
 * 老师 ---发布错题微课数据
 * 
 */
@CrossOrigin
@RestController
public class MistakesQuesWeikechengCrtController extends YxyApiBaseController {

    @Autowired
    private YxyResResourceRepository weikeRepository;

    @Autowired
    private TeaMistakesQuesRepository teaMistakesQuesRepository;

    @Autowired
    private YxyResWeikeKnowRepository weikeknowRepository;

    @Autowired
    private YxyKnowledgeRepository knowRepository;

    @Autowired
    private YxyResResourceForEsReindexRepository esReindexRepository;

    @Autowired
    private YxyResBookRepository yxyResBookRepository;

    @RequestMapping(value = "/api_yw/manage/tec/teaching/weikecheng/mistakesweike/crt", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel req,
            RespModel respModel) {

        req.check();
        String userId = getProfile(request, response).getId();
        // 微课
        YxyResResource weikeResource = weikeRepository.findById(req.weikeId);
        Assert.notNull(weikeResource, "微课已不存在");
        Assert.isTrue(StringUtils.equals(userId, weikeResource.getUploaderId()), "这不是您的微课");
        // 微课信息
        weikeResource.setTitle(req.title);
        weikeResource.setViewScope(1);
        weikeResource.setStatus(1);
        if (StringUtils.isBlank(req.cover)) {
            // 默认图片
            List<String> imgList = new ArrayList<String>();
            imgList.add("https://yxcsp.91yunxiao.com/yxcsp/pull/811624024c1a8ed19a91886439d84b42.jpg");
            imgList.add("https://yxcsp.91yunxiao.com/yxcsp/pull/a9cc53a8f881d96b60cf324ba8acce6c.jpg");
            imgList.add("https://yxcsp.91yunxiao.com/yxcsp/pull/5851661ae0f28fe98a4a8a98f45a0ce1.jpg");
            imgList.add("https://yxcsp.91yunxiao.com/yxcsp/pull/bbcdd670b532318bb4c4193dcb0a66fc.jpg");
            imgList.add("https://yxcsp.91yunxiao.com/yxcsp/pull/705e22e6faf771b07c536b7ad5c7dae8.jpg");
            String cover = imgList.get(new Random().nextInt(4));
            weikeResource.setCover(cover);
        } else {
            weikeResource.setCover(req.cover);
        }
        weikeResource.setIsDelete(0);
        weikeResource = weikeRepository.save(weikeResource);
        // 关联知识点
        List<Integer> knowList = req.knoLevel3Id;
        boolean flag = false;
        if (CollectionUtils.isNotEmpty(knowList)) {
            flag = true;
            weikeknowRepository.deleteByWeikeId(req.weikeId);
        }
        for (Integer knowThreeId : knowList) {
            flag = true;
            YxyResWeikeKnow weikeKnow = new YxyResWeikeKnow();
            // 三级
            YxyKnowledge knowThree = knowRepository.findById(knowThreeId);
            // 二级
            Integer knoLevel2Id = knowThree.getParentId();
            YxyKnowledge knowTwo = knowRepository.findById(knoLevel2Id);
            // 一级
            Integer knoLevel1Id = knowTwo.getParentId();
            YxyKnowledge knowOne = knowRepository.findById(knoLevel1Id);

            weikeKnow.setKnowOneLevelId(knoLevel1Id + "");
            weikeKnow.setKnowOneLevelName(knowOne.getName());

            weikeKnow.setKnowTwoLevelId(knoLevel2Id + "");
            weikeKnow.setKnowTwoLevelName(knowTwo.getName());

            weikeKnow.setKnowId(knowThree.getId());
            weikeKnow.setKnowName(knowThree.getName());
            // 学段,学科

            TeaMistakesQues tmq = teaMistakesQuesRepository.findOne(req.mistakesId);
            YxyResBook book = yxyResBookRepository.findTop1BySubjectIdAndPhaseIdAndStatus(tmq.getSubject(),
                    tmq.getStage(), 1);

            weikeKnow.setStage(tmq.getStage());
            weikeKnow.setStageName(book.getPhaseName());
            weikeKnow.setWeikeSubject(tmq.getSubject());
            weikeKnow.setWeikeSubjectName(book.getSubjectName());
            weikeKnow.setWeikeId(weikeResource.getId());
            weikeknowRepository.save(weikeKnow);
        }

        if (flag) {
            YxyResResourceForEsReindex esIndex = new YxyResResourceForEsReindex();
            esIndex.setResourceId(weikeResource.getId());
            esReindexRepository.save(esIndex);
        }
        // 重建索引
        EsResourceUpdateUtil.updateEsResoure(req.weikeId);
        respModel = new RespModel();
        respModel.setMessage("发布微课成功");
        return respModel;
    }

    protected static class ReqModel extends YxyApiReqModel {

        public String weikeId;// 微课id

        public String title;// 微课名称

        public String mistakesId;// 错题id

        public String cover;// 封面

        public List<Integer> knoLevel3Id;// 三级知识点ids

        public void check() {
            Assert.notNull(StringUtils.defaultIfBlank(weikeId, null), "微课id不能为空");
            Assert.notNull(StringUtils.defaultIfBlank(title, null), "请填写标题");
            Assert.notNull(StringUtils.defaultIfBlank(mistakesId, null), "错题id不能为空");
            Assert.isTrue(CollectionUtils.isNotEmpty(knoLevel3Id), "请至少选择一个知识点！");
        }

    }

    protected static class RespModel extends YxyApiRespModel {

    }
}
